<?php

class logfactory {

    private $log_config;
    private $base_dir;

    public function __construct() {
        $this->log_config = getInstance()->loader->config('log');
        $this->base_dir = $this->log_config['base_dir'];
        $this->tryMkdir($this->base_dir);
    }

    public function recordError($msg) {
        $file = sprintf('log_%s', date('Ymd'));
        return $this->logMessage('error', $file, $msg);
    }

    public function recordMsg($bizName, $file, $msg) {
        $fullDir = sprintf('%s/%s', $this->base_dir, $bizName);
        if (!is_dir($fullDir) && !$this->tryMkdir($fullDir)) {
            return FALSE;
        }

        try {
            $fullpath = sprintf('%s/%s.log', $fullDir, $file);
            if (file_exists($fullpath) && !is_writeable($fullpath)) {
                chmod($fullpath, 0777);
            }
            return error_log(date('H:i:s') . ' | ' . $msg . "\n", 3, $fullpath);
        } catch (\Exception $e) {
            return FALSE;
        }
    }

    private function tryMkdir($dir) {
        if (is_dir($dir)) {
            return TRUE;
        }
        try {
            return mkdir($dir, 0777);
        } catch (\Exception $e) {
            return FALSE;
        }
    }
}
